package com.songqi.common.core.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2024/5/9 19:36
 */
public class TimeRangeValidator implements ConstraintValidator<TimeRange, String> {

    private String format = "yyyy-MM-dd HH:mm:ss yyyy-MM-dd HH:mm:ss";

    @Override
    public void initialize(TimeRange constraintAnnotation) {
        format = constraintAnnotation.format();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return isValidTimeIntervalFormat(value, format);
    }


    private boolean isValidTimeIntervalFormat(String timeInterval, String format) {
        String regex = format
                .replaceAll("yyyy", "\\\\d{4}")
                .replaceAll("MM", "\\\\d{2}")
                .replaceAll("dd", "\\\\d{2}")
                .replaceAll("HH", "\\\\d{2}")
                .replaceAll("mm", "\\\\d{2}")
                .replaceAll("ss", "\\\\d{2}")
                .replaceAll("\\s+", "\\\\s+");

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(timeInterval);
        return matcher.matches();
    }


}
